package cn.bugstack.domain.auth.service;

import cn.bugstack.domain.auth.adapter.port.ILoginPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信消息推送服务
 * @description 用于向用户发送发货和退款消息
 */
@Slf4j
@Service
public class WechatMessageService {

    @Resource
    private ILoginPort loginPort;
    /**
     * 发送发货消息
     * @param userId 用户ID
     * @param orderNo 订单号
     * @param productName 商品名称
     */
    public void sendDeliveryMessage(String userId, String orderNo, String productName) {
        try {
            Map<String, Map<String, String>> data = new HashMap<>();
            data.put("first", createField("您的订单已发货，请注意查收"));
            data.put("keyword1", createField(orderNo));
            data.put("keyword2", createField(productName));
            data.put("keyword3", createField("已发货"));
            data.put("remark", createField("感谢您的购买，如有问题请联系客服"));

            loginPort.sendTemplateMessage(userId, data, "3hDc1MSN3N1jqgNE33mVmXTfPNNa2B99DH7dYkIfrHE");
            log.info("发货消息发送成功 userId:{}, orderNo:{}, openid:{}", userId, orderNo, userId);
        } catch (Exception e) {
            log.error("发货消息发送失败 userId:{}, orderNo:{}", userId, orderNo, e);
        }
    }

    /**
     * 发送退款消息
     * @param userId 用户ID
     * @param orderNo 订单号
     * @param refundAmount 退款金额
     */
    public void sendRefundMessage(String userId, String orderNo, String refundAmount) {
        try {
            Map<String, Map<String, String>> data = new HashMap<>();
            data.put("first", createField("您的订单已退款成功"));
            data.put("keyword1", createField(orderNo));
            data.put("keyword2", createField(refundAmount));
            data.put("keyword3", createField("已退款"));
            data.put("remark", createField("退款将在1-3个工作日内到账，请注意查收"));

            loginPort.sendTemplateMessage(userId, data, "Ol0f1pWkVRSZQo8hqIOZQokkGEUEdCZfESxl41oziBM");
            log.info("退款消息发送成功 userId:{}, orderNo:{}, refundAmount:{}, openid:{}",
                    userId, orderNo, refundAmount, userId);
        } catch (Exception e) {
            log.error("退款消息发送失败 userId:{}, orderNo:{}", userId, orderNo, e);
        }
    }

    /**
     * 创建模板字段
     */
    private Map<String, String> createField(String value) {
        Map<String, String> field = new HashMap<>();
        field.put("value", value);
        field.put("color", "#173177");
        return field;
    }
}